#pragma once
#ifndef SPINLOCK_H

#define SPINLOCK_H

#include<iostream>
#include<atomic>

//自旋锁
class spinlock {
private:
	std::atomic_flag flag = ATOMIC_FLAG_INIT;
public:
	//禁用拷贝构造  赋值
	spinlock(const spinlock&) = delete;
	spinlock& operator=(const spinlock&) = delete;
	
	spinlock() = default;
	~spinlock() = default;

	//获取锁
	void Lock()
	{
		while (flag.test_and_set(std::memory_order_acquire))
		{

		}
	}
	void UnLock()
	{
		flag.clear(std::memory_order_acquire);
	}
	//尝试获取锁 非阻塞
	bool try_lock()
	{
		return !flag.test_and_set(std::memory_order_acquire);
	}

};
#endif // SPINLOCK_H